// 新增统计服务
package cn.sightsnow.zh.service;

import cn.sightsnow.zh.entity.EasyDlResult;
import cn.sightsnow.zh.repository.EasyDlResultRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class StatisticsService {

    private final EasyDlResultRepository easyDlResultRepository;

    public StatisticsService(EasyDlResultRepository easyDlResultRepository) {
        this.easyDlResultRepository = easyDlResultRepository;
    }

    public Map<String, Integer> getDailyWasteCount(LocalDate startDate, LocalDate endDate) {
        LocalDateTime startDateTime = startDate.atStartOfDay();
        LocalDateTime endDateTime = endDate.atTime(LocalTime.MAX);

        List<EasyDlResult> results = easyDlResultRepository.findByRecognitionTimeBetween(startDateTime, endDateTime);

        return results.stream()
                .collect(Collectors.groupingBy(
                        result -> result.getRecognitionTime().toLocalDate().toString(),
                        LinkedHashMap::new,
                        Collectors.collectingAndThen(Collectors.toList(), List::size)
                ));
    }

    public Map<String, Long> getWasteTypeStatistics(LocalDate startDate, LocalDate endDate, List<String> types) {
        // 设置默认时间范围（如果未指定）
        // 修改后的时间范围初始化
        LocalDateTime startDateTime = (startDate != null) ?
                startDate.atStartOfDay() : LocalDateTime.of(1800, 1, 1, 0, 0); // 默认查全部历史数据，日期为1800年1月1日

        LocalDateTime endDateTime = (endDate != null) ?
                endDate.atTime(LocalTime.MAX) : LocalDateTime.now().plusYears(100); // 包含未来数据

        // 查询时间范围内的所有识别结果
        List<EasyDlResult> results = easyDlResultRepository.findByRecognitionTimeBetween(startDateTime, endDateTime);

        // 根据指定类型过滤结果
        Stream<EasyDlResult> resultStream = results.stream()
                .filter(result -> result.getSort_result_name() != null && !result.getSort_result_name().isEmpty());

        // 如果指定了类型，则进行过滤
        if (types != null && !types.isEmpty()) {
            resultStream = resultStream.filter(result -> types.contains(result.getSort_result_name()));
        }

        // 统计各类型的数量
        return resultStream.collect(Collectors.groupingBy(
                EasyDlResult::getSort_result_name,
                LinkedHashMap::new,
                Collectors.counting()
        ));
    }
}